<template>
  <el-upload action="#" :on-success="handleAvatarSuccessFace" :limit="1" :name="'files'" list-type="picture-card"
    :data="{ isConvert: false }" :before-upload="beforeAvatarUploadFace" :auto-upload="true" class="avatar-uploader"
    :show-file-list="false">
    <div v-if="modelValue" class="avatar">
      <img :src="modelValue" class="avatar" />
      <div class="avatar-bg neu-center neu-color-white">重新上传</div>
    </div>
    <el-icon v-else class="avatar-uploader-icon">
      <plus />
    </el-icon>
  </el-upload>
</template>
<script>
import ObsClient from 'esdk-obs-browserjs'
export default {
  name: 'ImageUpload',
  emits: ['update:modelValue'],
  data () {
    return {
      loading: true,
      access_key_id: '43I9JLFQGK4HTIVS4HHJ',
      secret_access_key: 'Y0CfSExq0PmgokPwvu415kg6S5vEBWfeZRhaqMhq',
      bucketName: 'neuedu-expo-test', // 桶名
      serverUrl: 'https://obs.cn-north-4.myhuaweicloud.com', // 服务器地址
      server: 'obs.cn-north-4.myhuaweicloud.com',
    }
  },
  props: {
    maxSize: {
      type: Number,
      default: 5
    },
    modelValue: {
      type: String,
      default: '',
    },
  },
  watch: {
    modelValue: {
      immediate: true,
      handler () { },
    },
  },
  mounted () { },
  methods: {
    timestampToTime () {
      var date = new Date() //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear() + '/'
      var M =
        (date.getMonth() + 1 < 10
          ? '0' + (date.getMonth() + 1)
          : date.getMonth() + 1) + '/'
      var D =
        (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + '/'
      return Y + M + D
    },
    timestampTime () {
      var date = new Date() //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear()
      var M =
        date.getMonth() + 1 < 10
          ? '0' + (date.getMonth() + 1)
          : date.getMonth() + 1
      var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      var h = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
      var m =
        date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
      var s =
        date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
      return Y + M + D + h + m + s
    },
    // 图片上传相关
    beforeAvatarUploadFace (file) {
      let isPass = true
      var date = new Date()
      // 取文件名
      const n = file.name.lastIndexOf(".")
      const fileName = file.name.substr(0, n)
      // 文件后缀
      const type = file.name.substr(n + 1, file.name.length)
      const timestampFileName =
        this.timestampToTime(date) +
        fileName +
        '_' +
        this.timestampTime(date) +
        '.' +
        type
      const fileNameLength = file.name.length > 200
      const isJPG =
        /\.jpeg$/.test(file.name) ||
        /\.png$/.test(file.name) ||
        /\.JPEG$/.test(file.name) ||
        /\.PNG$/.test(file.name) ||
        /\.JPG$/.test(file.name) ||
        /\.jpg$/.test(file.name) ||
        /\.BMP$/.test(file.name) ||
        /\.bmp$/.test(file.name)
      const isLt2M = file.size / 1024 / 1024 < this.maxSize
      if (!isJPG) {
        this.$message.error('请选择正确的图片格式')
        isPass = false
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过' + this.maxSize + 'MB!')
        isPass = false
      }
      if (fileNameLength) {
        this.$message.error('上传图片名称不能超过200个字符!')
        isPass = false
      }
      if (isPass) {
        // 上传华为云
        var obsClient = new ObsClient({
          access_key_id: this.access_key_id,
          secret_access_key: this.secret_access_key,
          server: this.serverUrl,
        })
        obsClient.putObject(
          {
            Bucket: this.bucketName, // 桶名
            Key: timestampFileName, // 文件名
            SourceFile: file,
            ContentType: 'text/plain',
          },
          (err, result) => {
            if (err) {
              this.$message.error({
                message: '上传失败，请重试',
              })
            } else {
              if (result.CommonMsg.Status < 300) {
                // 上传成功后，文件地址
                const fileUrl =
                  'https://' +
                  this.bucketName +
                  '.' +
                  this.server +
                  '/' +
                  timestampFileName
                this.$emit('update:modelValue', fileUrl)
                this.$message.success({
                  message: '文件上传成功！',
                })
              } else {
                this.$message.error({
                  message: '上传失败，请重试',
                })
              }
            }
          }
        )
      }
      return false
    },
    handleAvatarSuccessFace (res) {
    },
  },
}
</script>
<style lang="scss" scoped>
.avatar-uploader {
  text-align: center;
  position: relative;

  :deep(.el-upload--picture-card) {
    width: 122px;
    height: 122px;
    // border-radius: 50%;
    line-height: 118px;
  }
}

.avatar {
  width: 120px;
  height: 120px;

  // border-radius: 50%;
  &:hover .avatar-bg {
    display: block;
  }

  .avatar-bg {
    width: 120px;
    height: 120px;
    // border-radius: 50%;
    display: none;
    background-color: #00000088;
  }
}

.avatar-uploader-icon svg {
  margin-top: 47px;
  /* (178px - 28px) / 2 - 1px */
}

.el-upload--picture-card i {
  margin-top: 0px !important;
}

.neu-center {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate3d(-50%, -50%, 0);
}

.neu-color-white {
  color: white;
}
</style>
